import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authAPI, DataSyncManager } from '@/api'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('merchant_token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('merchant_user') || '{}'))
  const dataSyncManager = ref(null)

  const isLoggedIn = computed(() => !!token.value)

  const login = async (credentials) => {
    try {
      // 尝试真实API登录
      let response
      try {
        response = await authAPI.login(credentials)
        if (response.success !== false) {
          // API登录成功
          token.value = response.token
          userInfo.value = {
            ...response.user,
            role: response.user.role || 'MERCHANT',
            storeName: response.user.storeName || '商家店铺'
          }
        } else {
          throw new Error(response.message || 'API登录失败')
        }
      } catch (apiError) {
        console.warn('API登录失败，使用模拟登录:', apiError.message)
        // 降级到模拟登录
        response = await mockLogin(credentials)
        if (response.success) {
          token.value = response.data.token
          userInfo.value = {
            ...response.data.user,
            role: 'MERCHANT'
          }
        } else {
          return { success: false, message: response.message }
        }
      }
      
      localStorage.setItem('merchant_token', token.value)
      localStorage.setItem('merchant_user', JSON.stringify(userInfo.value))
      localStorage.setItem('userId', userInfo.value.id)
      
      // 初始化数据同步
      initDataSync()
      
      return { success: true }
    } catch (error) {
      console.error('登录错误:', error)
      return { success: false, message: '登录失败，请重试' }
    }
  }

  const logout = () => {
    // 断开数据同步连接
    if (dataSyncManager.value) {
      dataSyncManager.value.disconnect()
      dataSyncManager.value = null
    }
    
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('merchant_token')
    localStorage.removeItem('merchant_user')
    localStorage.removeItem('userId')
  }

  const updateUserInfo = (newUserInfo) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    localStorage.setItem('merchant_user', JSON.stringify(userInfo.value))
  }

  // 初始化数据同步连接
  const initDataSync = () => {
    if (userInfo.value.id && !dataSyncManager.value) {
      dataSyncManager.value = new DataSyncManager()
      
      // 添加数据更新监听器
      dataSyncManager.value.addListener('order', (data) => {
        console.log('订单数据更新:', data)
        // 触发UI更新
        window.dispatchEvent(new CustomEvent('orderUpdate', { detail: data }))
      })
      
      dataSyncManager.value.addListener('store', (data) => {
        console.log('店铺数据更新:', data)
        window.dispatchEvent(new CustomEvent('storeUpdate', { detail: data }))
      })
      
      dataSyncManager.value.addListener('product', (data) => {
        console.log('商品数据更新:', data)
        window.dispatchEvent(new CustomEvent('productUpdate', { detail: data }))
      })
      
      dataSyncManager.value.addListener('notification', (data) => {
        console.log('收到通知:', data)
        window.dispatchEvent(new CustomEvent('notification', { detail: data }))
      })
      
      // 连接WebSocket
      dataSyncManager.value.connect(userInfo.value.id, userInfo.value.role || 'MERCHANT')
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    logout,
    updateUserInfo,
    initDataSync
  }
})

// 模拟登录API
const mockLogin = (credentials) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 模拟商家账号验证
      const validAccounts = [
        { username: 'merchant1', password: '123456', storeId: 1, storeName: '美味餐厅' },
        { username: 'merchant2', password: '123456', storeId: 2, storeName: '川香小厨' },
        { username: 'test', password: '123456', storeId: 3, storeName: '测试餐厅' }
      ]

      const account = validAccounts.find(
        acc => acc.username === credentials.username && acc.password === credentials.password
      )

      if (account) {
        resolve({
          success: true,
          data: {
            token: 'mock_merchant_token_' + Date.now(),
            user: {
              id: account.storeId,
              username: account.username,
              storeName: account.storeName,
              storeId: account.storeId,
              avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
              phone: '13800138000',
              email: 'merchant@example.com'
            }
          }
        })
      } else {
        resolve({
          success: false,
          message: '用户名或密码错误'
        })
      }
    }, 1000)
  })
} 